<?php

namespace app\controller\api\store\merchant;

use app\common\helpers\ImageUtil;
use app\common\model\store\order\StoreOrderReceipt;
use app\common\model\system\merchant\FinancialRecord;
use app\common\model\system\merchant\FinancialWechat;
use app\common\repositories\store\ExcelRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\system\CacheRepository;
use app\common\repositories\system\merchant\FinancialRecordRepository;
use app\common\repositories\system\merchant\FinancialWechatRepository;
use app\common\repositories\system\merchant\MerchantRepository;
use app\validate\merchant\DeliveryStationValidate;
use crmeb\services\DeliverySevices;
use crmeb\services\easywechat\combinePay\Client;
use crmeb\services\ExcelService;
use crmeb\services\SwooleTaskService;
use crmeb\services\WechatService;
use think\App;
use crmeb\basic\BaseController;
use app\common\repositories\delivery\DeliveryExpressStationRepository;
use app\common\repositories\delivery\DeliveryStationRepository;
use app\validate\merchant\DeliveryExpressStationValidate;
use think\exception\ValidateException;
use think\facade\Db;

class FinanceRecords extends BaseController
{
    protected $merId;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->merId = $this->request->route('merId');
    }

    /**
     * @param FinancialRecordRepository $repository
     * @return mixed
     * @author: fupeng
     * @day: 2024/1/4
     * 资金流水
     */
    public function lst(FinancialRecordRepository $repository)
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['keyword', 'date']);
        $where['mer_id'] = $this->merId;
        $where['financial_type'] = ['order', 'mer_accoubts', 'brokerage_one', 'brokerage_two', 'refund_brokerage_one', 'refund_brokerage_two', 'refund_order','order_platform_coupon','order_svip_coupon'];
        return app('json')->success($repository->getList($where, $page, $limit));
    }

    public function title(FinancialRecordRepository $repository ,CacheRepository $CacheRepository)
    {
        $Merchant = app()->make(MerchantRepository::class)->get($this->merId);
        $fundBalance = WechatService::create()->combinePay()->fundBalance($Merchant->sub_mchid);
        $where = $this->request->params(['date']);
        $where['is_mer'] = $this->merId?? 0 ;
        $coupon = $repository->search($where)->where('financial_type','in',['order_platform_coupon','order_svip_coupon'])->sum('number');
        return app('json')->success([
            'delivery_balance' =>$Merchant->delivery_balance,
            'ot_margin' =>$Merchant->ot_margin,
            'margin' =>$Merchant->margin,
            'platform_coupon' =>$coupon,
            'total_amount'=> bcdiv(bcadd($fundBalance['pending_amount'] ,$fundBalance['available_amount']),100,2),
            'available_amount' =>bcdiv($fundBalance['available_amount'],100,2), //可用余额
            'pending_amount' => bcdiv($fundBalance['pending_amount'],100,2),
            'wechat_sft_rule'=>$CacheRepository->getResult('wechat_sft_rule')
        ]);
    }

    //收付通提现
    public function withdraw()
    {
        $Merchant = app()->make(MerchantRepository::class)->get($this->merId);
        $fundBalance = WechatService::create()->combinePay()->fundBalance($Merchant->sub_mchid);
        $info = (new FinancialWechat())->where(['withdraw_status'=>'INIT','mer_id'=>$this->merId])->find();
        if($info){
            throw new ValidateException('提现失败,联系系统管理员');
        }
        if(!isset($fundBalance['available_amount'])){
            throw new ValidateException('提现余额查询失败');
        }
        $available_amount = bcdiv($fundBalance['available_amount'],100,2);

        $param = $this->request->params(['amount', ['remark','']]);
        if(!isset($param['amount'])){
            throw new ValidateException('提现金额必传');
        }
         if($param['amount'] > $available_amount){
             throw new ValidateException('提现余额不足');
         }
        $out_request_no = app()->make(FinancialWechatRepository::class)->getSn();
         $uid = $this->request->uid();
        Db::transaction(function () use ($out_request_no,$available_amount,$param,$uid) {
            (new FinancialWechat())->insert(
                [
                    'out_request_no'=>$out_request_no,
                    'mer_money'=>$available_amount - $param['amount'],
                    'extract_money'=>$param['amount'],
                    'account_type'=>'BASIC',
                    'mer_id'=>$this->merId,
                    'create_time'=>date('Y-m-d H:i:s'),
                    'mark'=>$param['remark'],
                    'uid'=>$uid,
                ]
            );
        });
         $data = [
            'account_type'=>'BASIC',
            'sub_mchid'=>$Merchant->sub_mchid,
            'out_request_no'=>$out_request_no,
            'amount'=>intval(strval($param['amount']  * 100)),
        ];
        if(!isset($param['amount']) && $param['amount']){
            $data['remark'] = $param['remark'];
        }
        WechatService::create()->combinePay()->fundWithdraw($data);
        $res = WechatService::create()->combinePay()->fundWithdrawNo($Merchant->sub_mchid,$out_request_no);
        if(isset($res['status'])){
            (new FinancialWechat())
                ->where(['out_request_no'=>$out_request_no,'mer_id'=>$this->merId])
                ->save([
                    'account_bank'=>$res['account_bank'],
                    'account_number'=>$res['account_number'],
                    'withdraw_status'=>$res['status'],
                    'reason'=>$res['reason'],
                    'update_time'=>$res['update_time'],
                ]);
            return app('json')->success('预约提现申请成功');
        }
        throw new ValidateException('提现失败请联系管理员');
    }

    //收付通查询提现状态
    public function withdrawStatus($id)
    {
        $Merchant = app()->make(MerchantRepository::class)->get($this->merId);
        $FinancialWechat = app()->make(FinancialWechatRepository::class)->get($id);
        if(!$FinancialWechat)   throw new ValidateException('数据不存在');
        if($FinancialWechat->withdraw_status == 'SUCCESS')  return app('json')->success(Client::$withdraw_status[$res['status']]??'未知');
        $res = WechatService::create()->combinePay()->fundWithdrawNo($Merchant->sub_mchid, $FinancialWechat->out_request_no);
        if(isset($res['status'])){
              if($res['status'] != $FinancialWechat->withdraw_status){
                  $FinancialWechat->save([
                      'account_bank'=>$res['account_bank'],
                      'account_number'=>$res['account_number'],
                      'withdraw_status'=>$res['status'],
                      'reason'=>$res['reason'],
                      'update_time'=>$res['update_time'],
                  ]);
              }
            return app('json')->success(Client::$withdraw_status[$res['status']]??'未知');
        }
        throw new ValidateException('查询失败');
    }


    /**
     * @param FinancialWechatRepository $repository
     * @return void
     * @author: fupeng
     * @day: 2024/1/4
     *
     */
    public function withdrawLst(FinancialWechatRepository $repository)
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['keyword', 'date', 'start_time', 'end_time']);
        $where['mer_id'] = $this->merId;
        return app('json')->success($repository->getList($where, $page, $limit));
    }


    /**
     * TODO 列表
     * @return \think\response\Json
     * @author Qinii
     * @day 3/23/21
     */
    public function getList(FinancialRecordRepository $repository)
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params([['type',1],'date']);
        $where['is_mer'] = $this->merId;
        $data = $repository->getAdminList($where,$page, $limit);
        return app('json')->success($data);
    }


    /**
     * @param $type
     * @param FinancialRecordRepository $repository
     * @return mixed
     * @author: fupeng
     * @day: 2024/1/5
     */
    public function accountsDetail($type,FinancialRecordRepository $repository)
    {
        $date = $this->request->param('date');
        $where['date'] = empty($date) ? date('Y-m-d',time()) : $date ;
        $where['is_mer'] = $this->merId ;
        if($this->merId){
            $data = $repository->merDetail($type,$where);
        }else{
            $data = $repository->adminDetail($type,$where);
        }

        return app('json')->success($data);
    }

    /**
     * @param $type
     * @return mixed
     * @author: fupeng
     * @day: 2024/1/5
     * 导出文件
     */
    public function exportDetail($type)
    {
        [$page, $limit] = $this->getPage();
        $date = $this->request->param('date');
        $where['date'] = empty($date) ? date('Y-m-d',time()) : $date ;
        $where['type'] = $type;
        $where['is_mer'] = $this->merId;
        $data = app()->make(ExcelService::class)->exportFinancial($where,$page,$limit);
        $_path =  app()->make(ExcelService::class)->export(null,'financeRecord',$data['header'],$data['title'],$data['export'],$data['filename'],$data['foot']);
//         ob_clean();
//         echo $_path;
        return app('json')->success(ImageUtil::handle('/'.$_path));

    }


}
